﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Mvc;
using blacksoft.Models;
using System.Threading;
using System.Globalization;
using System.Data.Entity.Core.Objects;
using System.Data.Entity.Validation;

using Microsoft.Reporting.WebForms;
using System.IO;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
using blacksoft.Constantes;


namespace blacksoft.Controllers
{
    public class ReporteVentasController : Controller
    {
        private inf245travelbusEntities db = new inf245travelbusEntities();
        //
        // GET: /Report/
        public ActionResult Index()
        {
            //NO ESTOY LOGUEADO EN EL SISTEMA
            if (Session["Permisos"] == null)
            {
                TempData["LogueatePrimero"] = SystemField.NO_LOGUEADO;
                return RedirectToAction("Index", "ValidarLogin");
            }
            //ESTOY LOGUEADO PERO NO TENGO PERMISO PARA REALIZAR ESTA ACCION
            if (!PerfilsController.TienePermiso((int)Session["Permisos"], PerfilsController.VENTA))
            {
                TempData["SinPermiso"] = SystemField.SIN_PERMISO;
                return RedirectToAction("Index", "MainPageEmployes");
            }
            var lst_terminales = new List<string>();
            var qry_terminales = from t in db.Terminal
                                 select new{t.Nombre, t.IDTerminal};
            ViewBag.cb3 = new SelectList(qry_terminales,"IDTerminal","Nombre");

            return View();
        }

        [HttpPost]
        public ActionResult Reporte(FormCollection form)
        {
            //NO ESTOY LOGUEADO EN EL SISTEMA
            if (Session["Permisos"] == null)
            {
                TempData["LogueatePrimero"] = SystemField.NO_LOGUEADO;
                return RedirectToAction("Index", "ValidarLogin");
            }
            //ESTOY LOGUEADO PERO NO TENGO PERMISO PARA REALIZAR ESTA ACCION
            if (!PerfilsController.TienePermiso((int)Session["Permisos"], PerfilsController.VENTA))
            {
                TempData["SinPermiso"] = SystemField.SIN_PERMISO;
                return RedirectToAction("Index", "MainPageEmployes");
            }
            try
            {
                String fechaInicio = form["cb1"];
                String fechaFin = form["cb2"];
                String terminal = form["cb3"];
                String id = form["ddl_formato"]; //PDF, Excel, Word, Image

                if (String.Compare(fechaInicio,  fechaFin)>0 )
                {
                    TempData["index_failure"] = "La fecha inicial debe ser menor a la final";
                    return RedirectToAction("Index");
                }
                //validar campos correctos

                LocalReport lr = new LocalReport();
                lr.ReportPath = Path.Combine(Server.MapPath("~/Report"), "ReporteVentas.rdlc");

                List<ReportParameter> parameters = new List<ReportParameter>();
                parameters.Add(new ReportParameter("FechaInicio", fechaInicio));
                parameters.Add(new ReportParameter("FechaFinal", fechaFin));
                parameters.Add(new ReportParameter("Terminal", terminal));
                lr.SetParameters(parameters);

                SqlCommand cmdLatest = OpenConnection("sp_reporteVenta");
                cmdLatest.Parameters.AddWithValue("@fechaInicio", fechaInicio);
                cmdLatest.Parameters.AddWithValue("@fechaFinal", fechaFin);
                cmdLatest.Parameters.AddWithValue("@terminal", terminal);
                DataSet dt = GetDataSet(cmdLatest);

                ReportDataSource rd = new ReportDataSource("DataSetReporteVentas", dt.Tables[0]);
                lr.DataSources.Clear();
                lr.DataSources.Add(rd);
                lr.Refresh();

                string reportType = id;
                string mimeType;
                string encoding;
                string fileNameExtension;

                string deviceInfo =
                "<DeviceInfo>" +
                "  <OutputFormat>" + id + "</OutputFormat>" +
                "  <PageWidth>8.5in</PageWidth>" +
                "  <PageHeight>11in</PageHeight>" +
                "  <MarginTop>0.5in</MarginTop>" +
                "  <MarginLeft>1in</MarginLeft>" +
                "  <MarginRight>1in</MarginRight>" +
                "  <MarginBottom>0.5in</MarginBottom>" +
                "</DeviceInfo>";

                Warning[] warnings;
                string[] streams;
                byte[] renderedBytes;
            
                renderedBytes = lr.Render(
                        reportType,
                        deviceInfo,
                        out mimeType,
                        out encoding,
                        out fileNameExtension,
                        out streams,
                        out warnings);
                return File(renderedBytes, mimeType);
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine("Exception:");
                System.Diagnostics.Debug.WriteLine(e.ToString());
            }

            return null;
            
        }

        public SqlCommand OpenConnection(string strSpName)
        {
            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["inf245travelbusConnectionString"].ConnectionString);
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = strSpName;
            cmd.Connection = con;
            cmd.CommandType = CommandType.StoredProcedure;
            con.Open();
            return cmd;
        }
        public DataSet GetDataSet(SqlCommand cmd)
        {
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds);
            return ds;
        }
	}
}